package com.zw.design.pattern.creational.structural.proxy.dynamicproxy;

import com.zw.design.pattern.creational.structural.proxy.Order;
import com.zw.design.pattern.creational.structural.proxy.db.DataSourceContextHolder;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/***
 * 动态代理
 */
public class OrderServiceDynamicProxy implements InvocationHandler {

    private Object target;

    public OrderServiceDynamicProxy(Object target) {
        this.target = target;
    }


    public Object bind(){
        Class cls=target.getClass();
        return Proxy.newProxyInstance(cls.getClassLoader(), cls.getInterfaces(), this);
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        Object arg=args[0];
        beforeMethod(arg);
        Object invoke = method.invoke(target, args);
        afterMethod();
        return invoke;
    }

    private void beforeMethod(Object obj){
        Long userId=0L;
        System.out.println("动态代理 before coding");
        if (obj instanceof  Object){
            Order order= (Order) obj;
            userId=order.getUserId();
        }
        //开始业务操作
        int dbRouter= (int) (userId%2);
        System.out.println("dbRouter = 动态代理 db" + dbRouter +"处理数据");
        //TODO 设置dataSource 这里有spring 分库的思想 ;
        DataSourceContextHolder.setDbType(String.valueOf(dbRouter));
        System.out.println("动态代理 before  coding");

    }

    private void afterMethod(){
        System.out.println("动态代理 after code ");
    }

}
